package codetop;

import java.util.*;

public class lc3_无重复最长子串 {
    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcabcbb"));
    }
    public static int lengthOfLongestSubstring1(String s) {
        int ans = 0;
        int n = s.length();
        /**
         * 使用多个set
         */
        for (int i = 0; i < n; i++) {
            Set<Character> set = new HashSet<>();
            int j = i;
            while(j < n && !set.contains(s.charAt(j))){
                set.add(s.charAt(j));
                j++;
            }
            ans = Math.max(ans, j - i);
        }
        return ans;
    }

    public static int lengthOfLongestSubstring(String s) {
        int ans = 0;
        /**
         * HashMap + 滑动窗口
         */
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0, j = 0; j < s.length(); j++) {
            if(map.containsKey(s.charAt(j))){
                i = Math.max(map.get(s.charAt(j)) + 1, i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j);
        }
        return ans;
    }
}
